import {createSlice, PayloadAction} from '@reduxjs/toolkit';
import {AppThunk, RootState} from '../app/store';
import {AjaxUtil, WebApiData} from "../utils/AjaxUtil";

export const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

interface LoginSucInfo {
    userId: number;
    username: string;
    token: string;
}

/**
 * 定义数据结构
 */
interface GlobalState {
    loginSucInfo: LoginSucInfo | null;
}

/**
 * 初始值
 */
const initialState: GlobalState = {
    loginSucInfo: null,
};

export const GlobalSlice = createSlice({
    /**
     * 名称空间
     */
    name: 'Global',
    /**
     * 状态初始化
     */
    initialState,
    reducers: {
        /**
         * 增加一个指定值
         * @param state
         * @param action
         */
        setLoginSucInfo: (state, action: PayloadAction<LoginSucInfo>) => {
            state.loginSucInfo = action.payload;
        },
    }
});

export const {setLoginSucInfo} = GlobalSlice.actions;

type LoginResult = {
    id: number;
    token: string;
    username: string;
    age: number;
}
/**
 * 定义一个异步新增操作
 * const dispatch = useDispatch();
 * dispatch(incrementAsync(Number(incrementAmount) || 0))
 * @param amount
 */
export const loginAsync = (username: string, password: string): AppThunk => async (dispatch, getState) => {
    console.log('loginAsync')
    // 通过getState可以获取全局store状态
    const serverResp = await AjaxUtil.postBody<WebApiData<LoginResult>>({
        url: '/api/login/account',
        data: {username, password}
    })
    // @ts-ignore
    const webapiData = AjaxUtil.getWebApiData<WebApiData<LoginResult>>(serverResp)
    console.log(webapiData, 'webapiData')
    await dispatch(setLoginSucInfo({
        userId: webapiData.data.id,
        username: webapiData.data.username,
        token: webapiData.data.token
    }));
};

/**
 * 获取指定命名空间下的指定属性的状态值, 最终要通过const count = useSelector(selectCount);获取
 * @param state
 */
export const selectLoginSucInfo = (state: RootState) => state.Global.loginSucInfo;

export default GlobalSlice.reducer;
